import { H3, serve, serveStatic, eventHandler, appendCorsHeaders, isPreflightRequest, appendCorsPreflightHeaders } from "h3";
import { stat, readFile } from "node:fs/promises";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import "./config.js";
import { generateQuizHandler } from "./routes/quiz.js";
import corsMiddleware from './middlewares/cors.js';
import { uploadHandler, downloadHandler } from "./routes/sync.js";


// Get __dirname equivalent in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = new H3();


// Global CORS middleware
app.use(corsMiddleware);

// Resolve dist directory path (one level up from server/)
const distPath = join(__dirname, "..", "dist");

// API routes
app.use("/api/quiz/generate", generateQuizHandler);
app.use("/api/sync/upload", uploadHandler);
app.use("/api/sync/download", downloadHandler);

// Serve static files from dist directory
app.use("/**", (event) => {
    return serveStatic(event, {
        indexNames: ["/index.html"],
        getContents: (id) => readFile(join(distPath, id)),
        getMeta: async (id) => {
            const stats = await stat(join(distPath, id)).catch(() => { });
            //@ts-ignore
            if (stats?.isFile()) {
                return {
                    size: stats.size,
                    mtime: stats.mtimeMs,
                };
            }
        },
    });
});

const port = process.env.PORT || 3000;
serve(app, { port });
console.log(`🚀 Server running at http://localhost:${port}`);
console.log(`📁 Serving static files from: ${distPath}`);